package com.yupi.moonBI.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.moonBI.annotation.AuthCheck;
import com.yupi.moonBI.common.BaseResponse;
import com.yupi.moonBI.common.DeleteRequest;
import com.yupi.moonBI.common.ErrorCode;
import com.yupi.moonBI.common.ResultUtils;
import com.yupi.moonBI.constant.CommonConstant;
import com.yupi.moonBI.constant.UserConstant;
import com.yupi.moonBI.exception.BusinessException;
import com.yupi.moonBI.exception.ThrowUtils;
import com.yupi.moonBI.manager.RedisLimiterManager;
import com.yupi.moonBI.model.dto.chart.*;
import com.yupi.moonBI.model.entity.Chart;
import com.yupi.moonBI.model.entity.User;
import com.yupi.moonBI.model.vo.BIResponse;
import com.yupi.moonBI.service.ChartService;
import com.yupi.moonBI.service.UserService;
import com.yupi.moonBI.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.util.List;

import static com.yupi.moonBI.common.ErrorCode.NOT_FOUND_ERROR;
import static com.yupi.moonBI.constant.RedisConstant.CHART_CHCHE_ID;

/**
 * 图表数据分析接口
 * @author 苦行修士
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);

        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @CacheEvict(value = "charts", key = "#chartUpdateRequest.id")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, NOT_FOUND_ERROR);
        String name = chart.getName();
        String chartType = chart.getChartType();
        String genChart = chart.getGenChart();
        String goal = chart.getGoal();
        //chart部分字段数据更新
        UpdateWrapper<Chart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", chart.getId());
        if (ObjectUtils.isNotEmpty(name)) {
            updateWrapper.set("name", name);
        }
        if (ObjectUtils.isNotEmpty(chartType)) {
            updateWrapper.set("chartType", chartType);
        }
        if (ObjectUtils.isNotEmpty(genChart)) {
            updateWrapper.set("genChart", genChart);
        }
        if (ObjectUtils.isNotEmpty(goal)) {
            updateWrapper.set("goal", goal);
        }
        boolean result = chartService.update(null, updateWrapper);

        //判断是否更新成功
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        log.info("更新图表{}成功", id);
        String chartCacheId = CHART_CHCHE_ID + id;
        Boolean delete = stringRedisTemplate.delete(chartCacheId);
        if (Boolean.TRUE.equals(delete)) {
            log.info("删除Redis缓存图表{}成功", id);
        } else {
            log.info("删除Redis缓存图表{}失败",id);
        }
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 缓存优化后的获取图表信息
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/cache/get")
    @Cacheable(value = "charts", key = "#id")
    public BaseResponse<Chart> getChartByIdCache(long id, HttpServletRequest request) {

        Chart chartByIdCache = chartService.getChartByIdCache(id);
        //返回成功结果
        return ResultUtils.success(chartByIdCache);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 获取缓存图表列表（封装类）
     *
     * @return
     */
    @PostMapping("/list/cache")
    public BaseResponse<List<Chart>> listChartByCache() {

        List<Chart> chartList = chartService.listChartByCacheService();
        return ResultUtils.success(chartList);
    }

    /**
     * 分页获取缓存图表列表信息
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/cache/page")
    public BaseResponse<List<Chart>> listChartByCachePage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                          HttpServletRequest request) {

        List<Chart> chartList = chartService.listChartByCachePage(chartQueryRequest, request);
        return ResultUtils.success(chartList);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);

        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        //用户更新了图表，需要更新缓存
        stringRedisTemplate.delete(CHART_CHCHE_ID + chart.getId());
        return ResultUtils.success(result);
    }

    /**
     * 🐟聪明AI智能分析
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BIResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) throws FileNotFoundException {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        User loginUser = userService.getLoginUser(request);

        //限流判断——得先获取到用户信息
        redisLimiterManager.doRateLimit("genChartByAi" + loginUser.getId());

        BIResponse biResponse = chartService.genChartByAiService(multipartFile, genChartByAiRequest, loginUser);
        // 返回成功结果
        return ResultUtils.success(biResponse);
    }

    /**
     * 星火AI智能分析
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/genSpark")
    public BaseResponse<BIResponse> genChartBySparkAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) throws FileNotFoundException {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        User loginUser = userService.getLoginUser(request);

        //限流判断——得先获取到用户信息
        redisLimiterManager.doRateLimit("genChartBySparkAi" + loginUser.getId());

        BIResponse biResponse = chartService.genChartBySparkAiService(multipartFile, genChartByAiRequest, loginUser);
        // 返回成功结果
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析（异步线程池）
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/asycn")
    public BaseResponse<BIResponse> genChartByAiAsycn(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) throws FileNotFoundException {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        User loginUser = userService.getLoginUser(request);

        //限流判断——得先获取到用户信息
        redisLimiterManager.doRateLimit("genChartByAi" + loginUser.getId());

        BIResponse biResponse = chartService.genChartByAiAsycnService(multipartFile, genChartByAiRequest, loginUser);
        // 返回成功结果
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析（异步消息队列）
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/asycn/mq")
    public BaseResponse<BIResponse> genChartByAiAsycnMq(@RequestPart("file") MultipartFile multipartFile,
                                                        GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) throws FileNotFoundException {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();

        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长");

        User loginUser = userService.getLoginUser(request);

        //限流判断——得先获取到用户信息
        redisLimiterManager.doRateLimit("genChartByAi" + loginUser.getId());

        BIResponse biResponse = chartService.genChartByAiMQService(multipartFile, genChartByAiRequest, loginUser);


        // 返回成功结果
        return ResultUtils.success(biResponse);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        //如果查询请求为空，则返回查询包装器
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        //获取查询id
        Long id = chartQueryRequest.getId();
        //获取查询目标
        String goal = chartQueryRequest.getGoal();
        //获取查询图表类型
        String chartType = chartQueryRequest.getChartType();
        //获取查询名称
        String name = chartQueryRequest.getName();
        //获取查询用户id
        Long userId = chartQueryRequest.getUserId();
        //获取查询排序字段
        String sortField = chartQueryRequest.getSortField();
        //获取查询排序方向
        String sortOrder = chartQueryRequest.getSortOrder();

        //判断id是否为空，不为空则添加查询条件
        queryWrapper.ne(id != null && id > 0, "id", id);
        //判断目标是否为空，不为空则添加查询条件
        queryWrapper.eq(StringUtils.isNotEmpty(goal), "goal", goal);
        //判断名称是否为空，不为空则添加查询条件
        queryWrapper.like(StringUtils.isNotEmpty(name), "name", name);
        //判断图表类型是否为空，不为空则添加查询条件
        queryWrapper.eq(StringUtils.isNotEmpty(chartType), "chartType", chartType);
        //判断用户id是否为空，不为空则添加查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        //添加查询条件
        queryWrapper.eq("isDelete", false);
        //添加排序条件
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/searchChart/page")
    public BaseResponse<Page<Chart>> searchChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.searchChartByEs(chartQueryRequest);
        return ResultUtils.success(chartPage);
    }

}
